<?php


namespace app\service\utils;


use think\cache\driver\Redis;
use think\facade\Config;

class RedisService extends Redis
{
    /**
     * 实例化的对象,单例模式.
     * @var Redis
     */
    protected static $instance = [];
    protected $db;

    /**
     * 私有的构造函数 禁止直接实例化
     * RedisService constructor.
     * @param $db
     */
    public function __construct($db = 0)
    {
        $options = Config::get('cache.stores.redis');

        $options['select'] = $db;

        $this->db = $db;

        $this->options = array_merge($this->options, $options);

        parent::__construct();
    }

    /**
     * 提供对外实例化方法
     * @param int $db
     * @return mixed
     */
    public static function instance($db = 8)
    {
        if (!isset(self::$instance[$db])) {

            self::$instance[$db] = new self($db);

        }
        return self::$instance[$db];
    }

    /**
     * 禁止clone
     */
    private function __clone()
    {
    }

    /**
     * 析构函数
     */
    public function __destruct()
    {
        self::$instance[$this->db]->close();
        unset(self::$instance[$this->db]);
    }

    /**
     * 设置经纬度
     * @param $key
     * @param $schoolId
     * @param $lng
     * @param $lat
     * @return mixed
     */
    public function setSchoolLocationToRedis($key, $schoolId, $lng, $lat)
    {
        return $this->handler->geoadd($key, $lng, $lat, $schoolId);
    }

    /**
     * 获取所有成员
     * @param $key
     * @param $schoolId
     * @return mixed
     */
    public function getMemberLocationByKey($key, $schoolId)
    {
        return $this->handler->geopos($key, $schoolId);
    }

    /**
     * 获取范围内的所有成员
     * @param $key
     * @param $lng
     * @param $lat
     * @param $radius
     * @param string $unit
     * @param string $extend
     * @param string $sort
     * @return mixed
     */
    public function getMembersByDistance($key, $lng, $lat, $radius, $unit = 'km', $extend = 'WITHDIST', $sort = 'ASC')
    {
        $lat = floatval($lat);
        $lng = floatval($lng);
        return $this->handler->georadius($key, $lng, $lat, $radius, $unit, [$extend, 'SORT', $sort]);
    }

    /**
     * 格式化成员数组
     * @param $arr
     * @return array
     */
    public function formatLocation($arr): array
    {
        $keyArr = array_column($arr, 0);
        $valueArr = array_column($arr, 1);
        $values = array_combine($keyArr, $valueArr);
        return ['key' => $keyArr, 'value' => $values];
    }
}